<?php
/*
* Copyright 2010 Butin Kirill <kiryaka@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*         http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/


class FileManager
{
	/**
	 * @var DOMDocument
	 */
	protected $dir_tree;
	/**
	 * @var DOMDocument
	 */	
	protected $files_list;
	protected static $counter;
	protected $path  = "D:\\Work\\test";

	public function __construct()
	{
		$this->dir_tree = new DOMDocument("1.0", "utf-8");
		$this->files_list = new DOMDocument("1.0", "utf-8");
		$dir_root_node = $this->dir_tree->appendChild($this->dir_tree->createElement("tree"));
		$files_root_node = $this->files_list->appendChild($this->files_list->createElement("tree"));

		$this->refreshFilesTree($this->path, $dir_root_node, $files_root_node);
	}

	protected function refreshFilesTree($dir, DOMNode $dir_node, DOMNode $file_node){
		if ($dh = opendir($dir)) {
			while (($file = readdir($dh)) !== false) {
				if ($file == '.' || $file == '..') continue;
				$path = $dir."/".$file;
				if ( filetype($path) == 'dir' ){
					$subdir = $dir_node->appendChild($this->dir_tree->createElement("dir"));
					/* @var $subdir DOMElement*/
					$subdir->setAttribute("label", $file);
					$this->counter++;
					$subdir->setAttribute("id", $this->counter);
					$subdir->setAttribute("type", "dir");

					$file_sub_node = $this->files_list->documentElement->appendChild($this->files_list->createElement("dir"));
					$file_sub_node->setAttribute("parent", $this->counter);


					$this->refreshFilesTree($path, $subdir, $file_sub_node);
				}else{
					$c_file_node = $file_node->appendChild($this->files_list->createElement("file"));
					$c_file_node->setAttribute("label", $file);
					$c_file_node->setAttribute("type", $this->getTypeByName($file));
					$c_file_node->setAttribute("size", filesize($path));
				}
			}
			closedir($dh);
		}
	}

	protected function getTypeByName($file)
	{
		$path_info = pathinfo($file);
		if (strlen($path_info['extension']) > 0) return strtolower($path_info['extension']);
		return "file";
	}

	/**
	 * @return DOMDocument
	 */
	public function getDirTree(){
		return $this->dir_tree;
	}

	/**
	 * @return DOMDocument
	 */
	public function getFiles(){
		return $this->files_list;
	}
}